package timing.ukulele.user.receiver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import timing.ukulele.common.dictionary.ThirdPartyTypeEnum;
import timing.ukulele.user.model.WxMpMessageXmlModel;
import timing.ukulele.user.persistent.SysThirdPartyUser;
import timing.ukulele.user.service.SysThirdPartyUserService;
import timing.ukulele.user.util.WeixinMessageUtil;

import static timing.ukulele.user.config.TopicConfig.WX_MP_ROUTING;

@Component
@Slf4j
public class WxMpMessageReceiver {
    private final SysThirdPartyUserService userService;
    private final WeixinMessageUtil weixinMessageUtil;

    public WxMpMessageReceiver(SysThirdPartyUserService userService, WeixinMessageUtil weixinMessageUtil) {
        this.userService = userService;
        this.weixinMessageUtil = weixinMessageUtil;
    }

    @RabbitHandler
    @RabbitListener(queues = WX_MP_ROUTING)
    public void obtainUserDetail(WxMpMessageXmlModel wxMpMessageXmlModel) {
        log.info("收到了微信推送的消息", wxMpMessageXmlModel);
        String unionId = weixinMessageUtil.getUnionId(wxMpMessageXmlModel.getFromUserName());
        if (StringUtils.hasText(unionId)) {
            boolean exists = userService.lambdaQuery().eq(SysThirdPartyUser::getPlatId, wxMpMessageXmlModel.getFromUserName()).exists();
            if (!exists) {
                SysThirdPartyUser sysThirdpartyUser = new SysThirdPartyUser();
                sysThirdpartyUser.setPlatId(wxMpMessageXmlModel.getFromUserName());
                sysThirdpartyUser.setPlatSource(ThirdPartyTypeEnum.WX_MP.getValue());
                sysThirdpartyUser.setUnionId(unionId);
                sysThirdpartyUser.setDeleted(Boolean.FALSE);
                userService.save(sysThirdpartyUser);
            }
            weixinMessageUtil.sendMpAppCardMessage(wxMpMessageXmlModel.getFromUserName());
        }
    }
}
